package com.coocaa.x.uipackage.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import com.coocaa.x.framework.app.CoocaaActivity;

public class WaitingBar extends View {
    int width, height;
    int paddingLeft, paddingTop, paddingRight, paddingBottom;
    int rectWidth, rectHeight;
    Rect destRect;
    Paint mPaint;
    private int crtOffset;
    private int step;
    private Bitmap waitingBm;
    private boolean runningAnim = false;
    private int speed = CoocaaActivity.Div(4);

    public WaitingBar(Context context) {
        super(context);
        mPaint = new Paint();
    }

    public void setWaitingBitmap(Bitmap bm, int step) {
        this.waitingBm = bm;
        this.step = step;
        this.crtOffset = step;
        destRect = new Rect(paddingLeft, paddingTop, width - paddingRight,
                height - paddingBottom);
        rectWidth = width - paddingLeft - paddingRight;
        rectHeight = height - paddingTop - paddingBottom;
    }

    public void setWaitingBitmap(Bitmap bm, int step, int paddingLeft, int paddingTop,
                                 int paddingRight, int paddingBottom) {
        this.paddingLeft = paddingLeft;
        this.paddingTop = paddingTop;
        this.paddingRight = paddingRight;
        this.paddingBottom = paddingBottom;
        setWaitingBitmap(bm, step);
    }

    public void startAnim() {
        runningAnim = true;
    }

    public void stopAnim() {
        runningAnim = false;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        if (runningAnim && waitingBm != null) {
            canvas.drawBitmap(waitingBm, new Rect(crtOffset, 0, rectWidth + crtOffset, rectHeight), destRect, mPaint);
            if (crtOffset <= 0)
                crtOffset = step;
            else crtOffset -= speed;
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            invalidate();
        }
        super.onDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        this.width = w;
        this.height = h;
        destRect = new Rect(paddingLeft, paddingTop, width - paddingRight,
                height - paddingBottom);
        rectWidth = width - paddingLeft - paddingRight;
        rectHeight = height - paddingTop - paddingBottom;
        super.onSizeChanged(w, h, oldw, oldh);
    }

}
